package com.cdks.wuxiu.api.service.mysql;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cdks.wuxiu.api.component.constant.Constant;
import com.cdks.wuxiu.api.mapper.UserFriendInfoMapper;
import com.cdks.wuxiu.api.model.dto.UserFriendDTO;
import com.cdks.wuxiu.api.util.TimeUtils;
import com.cdks.wuxiu.entity.mysql.UserFriendInfo;

import java.util.List;

import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;


/**
 * 用户好友信息 服务实现类
 */
@Service
public class UserFriendInfoServiceImpl extends ServiceImpl<UserFriendInfoMapper, UserFriendInfo> implements UserFriendInfoService {
    private Long makeIdentity(long userId, long friendId)
    {
        String identity;
        if (userId > friendId)
        {
            identity  = String.valueOf(friendId) + String.valueOf(userId);
        }
        else
        {
            identity  = String.valueOf(userId) + String.valueOf(friendId);
        }

        return Long.parseLong(identity);
    }

    @Override
    public int request(long userId, long friendId) {
        try
        {
            UserFriendInfo info  = new UserFriendInfo();
            info.setIdentity(makeIdentity(userId, friendId));
            info.setCreateTime(TimeUtils.getTimeSecond());
            info.setUserId(userId);
            info.setFriendId(friendId);

            baseMapper.insert(info);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                return -1;
            }
        }        

        return 0;
    }

    @Override
    public int agree(long userId, long friendId) {
        UpdateWrapper<UserFriendInfo> wrapper = new UpdateWrapper<>();
        wrapper.lambda().eq(UserFriendInfo::getIdentity, makeIdentity(userId, friendId))
                        .set(UserFriendInfo::getStatus, Constant.ENABLE_YES);
        baseMapper.update(null, wrapper);

        return 0;
    }

    @Override
    public int delete(long userId, long friendId) {
        UpdateWrapper<UserFriendInfo> wrapper = new UpdateWrapper<>();
        wrapper.lambda().eq(UserFriendInfo::getIdentity, makeIdentity(userId, friendId));
        baseMapper.delete(wrapper);

        return 0;
    }

    @Override
    public List<UserFriendDTO> getList(long userId, long startId) {
        return baseMapper.getList(userId, startId, Constant.LIST_PAGE_SIZE);
    }

    @Override
    public UserFriendInfo queryByIdentity(long userId, long friendId) {
        QueryWrapper<UserFriendInfo> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(UserFriendInfo::getIdentity, makeIdentity(userId, friendId))
                        .eq(UserFriendInfo::getStatus, Constant.ENABLE_YES);
        
        return baseMapper.selectOne(wrapper);
    }
}
